package com.itbaizhan.openhis.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itbaizhan.openhis.constant.Constants;
import com.itbaizhan.openhis.domain.*;
import com.itbaizhan.openhis.dto.CareHistoryDto;
import com.itbaizhan.openhis.dto.CareOrderFormDto;
import com.itbaizhan.openhis.dto.CareOrderItemDto;
import com.itbaizhan.openhis.mapper.*;
import com.itbaizhan.openhis.service.CareHistoryService;
import com.itbaizhan.openhis.service.MedicinesService;
import com.itbaizhan.openhis.utils.IdGeneratorSnowflake;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.List;

/**
 *
 */
//@Service
@Service
public class CareHistoryServiceImpl extends ServiceImpl<CareHistoryMapper, CareHistory>
    implements CareHistoryService{

    @Autowired
    private RegistrationMapper registrationMapper;

    @Autowired
    private CareHistoryMapper careHistoryMapper;
    @Autowired
    private CareOrderMapper careOrderMapper;
    @Autowired
    private CareOrderItemMapper careOrderItemMapper;

    @Autowired
    private OrderChargeItemMapper orderChargeItemMapper;

    @Reference
    private MedicinesService medicinesService;//这在erp模块

    @Override
    public List<CareHistory> queryCareHistoryByPatientId(String patientId) {
        QueryWrapper<CareHistory> wrapper = new QueryWrapper<>();
        wrapper.eq(CareHistory.COL_PATIENT_ID,patientId);

        return careHistoryMapper.selectList(wrapper);
    }

    @Override
    public List<CareOrder> queryCareOrdersByChId(String chId) {
        QueryWrapper<CareOrder> wrapper = new QueryWrapper<>();
        wrapper.eq(CareOrder.COL_CH_ID,chId);
        return careOrderMapper.selectList(wrapper);
    }

    @Override
    public List<CareOrderItem> queryCareOrderItemsByCoId(String coId,String status) {
        QueryWrapper<CareOrderItem> wrapper = new QueryWrapper<>();
        wrapper.eq(CareOrderItem.COL_CO_ID,coId);
        wrapper.eq(StringUtils.isNotBlank(status),CareOrderItem.COL_STATUS,status);
        return careOrderItemMapper.selectList(wrapper);
    }

    @Override
    public CareHistory saveOrUpdateCareHistory(CareHistoryDto careHistoryDto) {
        CareHistory careHistory = new CareHistory();
        BeanUtil.copyProperties(careHistoryDto,careHistory);
        //对病历进行判断，如果存在，则更新，如果没有则增加
        if(StringUtils.isNotBlank(careHistory.getChId())){
            careHistoryMapper.updateById(careHistory);
        }else {
            //添加
            careHistory.setChId(IdGeneratorSnowflake.generatorIdWithProfix(Constants.ID_PROFIX_CH));
            careHistoryMapper.insert(careHistory);
        }

        return careHistory;
    }

    //根据挂号id查询病历信息
    @Override
    public CareHistory queryCareHistoryByRegId(String regId) {

        //这里不可以用careHistoryMapper.selectById()，因为id不是病历id
        QueryWrapper<CareHistory> wrapper = new QueryWrapper<>();
        wrapper.eq(CareHistory.COL_REG_ID,regId);
        return careHistoryMapper.selectOne(wrapper);
    }

    @Override
    public CareHistory queryCareHistoryByChId(String chId) {
        return careHistoryMapper.selectById(chId);
    }

    @Override
    public int saveCareOrderItem(CareOrderFormDto careOrderFormDto) {
        CareOrder careOrder =new CareOrder();
        BeanUtil.copyProperties(careOrderFormDto.getCareOrder(),careOrder);
        careOrder.setCreateBy(careOrderFormDto.getCareOrder().getSimpleUser().getUserName());
        careOrder.setCreateTime(DateUtil.date());
        int i = careOrderMapper.insert(careOrder);
        //保存详情表
        List<CareOrderItemDto> items = careOrderFormDto.getCareOrderItems();
        for(CareOrderItemDto item : items){
            CareOrderItem careOrderItem = new CareOrderItem();
            BeanUtil.copyProperties(item,careOrderItem);
            careOrderItem.setCoId(careOrder.getCoId());
            careOrderItem.setCreateTime(DateUtil.date());
            careOrderItem.setStatus(Constants.ORDER_STATUS_0);
            careOrderItem.setItemId(IdGeneratorSnowflake.generatorIdWithProfix(Constants.ID_PROFIX_ITEM));
            careOrderItemMapper.insert(careOrderItem);
        }
        return i;
    }

    @Override
    public CareOrderItem queryCareOrderItemsByItem(String itemId) {
        return careOrderItemMapper.selectById(itemId);
    }

    @Override
    public int deleteCareOrderItemById(String itemId) {
        CareOrderItem careOrderItem = careOrderItemMapper.selectById(itemId);
        //处方id
        String coId = careOrderItem.getCoId();
        int i = careOrderItemMapper.deleteById(coId);
        //删除处方后，要重新计算处方表价格
        QueryWrapper<CareOrderItem> wrapper = new QueryWrapper<>();
        wrapper.eq(CareOrderItem.COL_CO_ID,coId);
        //查询出处方详情，再遍历处方，把价格加起来
        List<CareOrderItem> careOrderItems = careOrderItemMapper.selectList(wrapper);
        if(careOrderItems != null && careOrderItems.size() >0){
            //重新计算处方价格,用BigDecimal计算，初始值为0
            BigDecimal allAmount = new BigDecimal("0");
            for(CareOrderItem orderItem : careOrderItems){
                allAmount = allAmount.add(orderItem.getAmount());
            }
            //根据coId查询处方表
            CareOrder careOrder = careOrderMapper.selectById(coId);
            careOrder.setAllAmount(allAmount);
            careOrderMapper.updateById(careOrder);
        }else {
            careOrderMapper.deleteById(coId);
        }

        return i;
    }

    @Override
    public int visitComplete(String regId) {
        Registration registration = new Registration();
        registration.setRegId(regId);
        registration.setRegStatus(Constants.REG_STATUS_3);
        return registrationMapper.updateById(registration);
    }

    @Override
    public String doMedicine(List<String> itemIds) {
       //1，根据详情id查询处方详情
        QueryWrapper<CareOrderItem> wrapper = new QueryWrapper<>();
        wrapper.in(CareOrderItem.COL_ITEM_ID,itemIds);
        List<CareOrderItem> careOrderItems = careOrderItemMapper.selectList(wrapper);
        StringBuffer stringBuffer = new StringBuffer();
        //2遍历orderItems,扣减库存
        for (CareOrderItem careOrderItem: careOrderItems){
            //扣减库存
           int i = medicinesService.deductionMedicinesStorage(Long.valueOf(careOrderItem.getItemRefId()),careOrderItem.getNum().longValue());//转为long型
            //扣减成功返回整数
            if(i >0){
                //处方详情表改为已完成状态
                careOrderItem.setStatus(Constants.ORDER_DETAILS_STATUS_3);
                careOrderItemMapper.updateById(careOrderItem);
                //收费详情表状态改为已完成
                OrderChargeItem orderChargeItem = new OrderChargeItem();
                orderChargeItem.setItemId(careOrderItem.getItemId());
                orderChargeItem.setStatus(Constants.ORDER_DETAILS_STATUS_3);
                orderChargeItemMapper.updateById(orderChargeItem);
            }else {
                stringBuffer.append("【"+careOrderItem.getItemName()+"】发药失败");
            }
        }
        if(StringUtils.isNotBlank(stringBuffer.toString())){
            //如果是空的，说明发药成功
            return null;
        }else {
            return stringBuffer.toString();
        }

    }

    @Override
    public List<CareOrderItem> queryCareOrderItemsByStatus(String coTypeCheck, String status) {
       QueryWrapper<CareOrderItem> wrapper = new QueryWrapper<>();
       wrapper.eq(CareOrderItem.COL_ITEM_TYPE,coTypeCheck);
       wrapper.eq(CareOrderItem.COL_STATUS,status);

        return careOrderItemMapper.selectList(wrapper);
    }

    @Override
    public CareOrder queryCareOrderByCoId(String coId) {
        return careOrderMapper.selectById(coId);
    }
}




